package com.huarun.module.airconditioning.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.huarun.common.BaseController;
import com.huarun.common.ResponseMessage;
import com.huarun.common.util.Constant;
import com.huarun.common.util.DateUtils;
import com.huarun.common.util.HttpUtil;
import com.huarun.common.util.ResultCodeEnum;
import com.huarun.common.util.SpringContextUtils;
import com.huarun.common.util.StringUtils;
import com.huarun.common.util.TimeParse;
import com.huarun.common.util.TokenUtil;
import com.huarun.module.airconditioning.bean.AirConditionerApply;
import com.huarun.module.airconditioning.bean.AirConditioning;
import com.huarun.module.airconditioning.bean.AirConditioningResult;
import com.huarun.module.airconditioning.bean.ApplyTime;
import com.huarun.module.airconditioning.bean.Room;
import com.huarun.module.airconditioning.bean.UseTime;
import com.huarun.module.airconditioning.service.IAirConditioningService;
import com.huarun.module.airconditioning.service.IAirConditioningTimeService;
import com.huarun.module.applyrecord.bean.ApplyRecord;
import com.huarun.module.applyrecord.service.IApplyRecordService;
import com.huarun.module.repair.bean.AddResult;
import com.huarun.module.user.bean.User;
import com.huarun.module.user.service.IUserService;

import io.swagger.annotations.ApiOperation;

/***
 * 
 * @author dzm
 * @创建时间 2018-10-29 16:13
 * @Description 空调加时
 */
@Controller
@RequestMapping("/wx/airCondition")
public class AirConditioningController extends BaseController {

	@Resource
	private IAirConditioningService airConditioningService;
	@Resource
	private IAirConditioningTimeService airConditioningTimeService;
	@Resource
	private IApplyRecordService applyRecordService;
	@Resource
	private IUserService userService;

	// 返回数据格式;{"ErrorCode":0,"Data":{"DetailData":[{"ApplyTypeRowGuid":"0","ApplyTypeName":"空调加时"},
	// {"ApplyTypeRowGuid":"1","ApplyTypeName":"货梯申请"},{"ApplyTypeRowGuid":"2","ApplyTypeName":"货物放行"}]},
	// "ErrorMessage":"成功"}
	@ApiOperation(value = "获取报事类型", notes = "获取报事类型")
	@RequestMapping(value = "/getWorkType", method = RequestMethod.GET)
	@ResponseBody
	public Object getWorkType(HttpServletRequest request, Map<String, Object> params) throws Exception {
		long time = System.currentTimeMillis();
		// 获取报事类型
		String url = Constant.WORK_TYPE;
		String token = TokenUtil.createToken(url, request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		System.out.println(Constant.BASE_URL + url);
		String data = HttpUtil.doGet(Constant.BASE_URL + url);

		return data;
	}

	// 调不同，提示token无效
	@ApiOperation(value = "获取设备列表", notes = "获取设备类型")
	@RequestMapping(value = "/getFacType", method = RequestMethod.GET)
	@ResponseBody
	public Object getFacType(HttpServletRequest request, Map<String, Object> params) throws Exception {
		long time = System.currentTimeMillis();
		// 获取报事类型
		String url = Constant.FAC_TYPE;
		String token = TokenUtil.createToken(url + "a843779a-bcc5-def2-e500-5b7fa4c4a1be", request, time, null);
		url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
		System.out.println(Constant.BASE_URL + url);
		String data = HttpUtil.doGet(Constant.BASE_URL + url);

		return data;
	}

	@ApiOperation(value = "获取工单列表(货物放行、空调加时）", notes = "获取工单列表(货物放行、空调加时）")
	@RequestMapping(value = "/getWorkOrderList", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<Object> getWorkOrderList(HttpServletRequest request,
			@RequestParam(required = false) Integer page, @RequestParam(required = false) Integer rows)
			throws Exception {
		ResponseMessage<Object> rm = new ResponseMessage<Object>();
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> param = new HashMap<>();
		param.put("openId", request.getHeader("openId"));
		User u = userService.getUserByParams(param);
		long time = System.currentTimeMillis();
		try {
			String workorderstate = request.getParameter("workorderstate");
			String startTime = request.getParameter("startTime");
			String endTime = request.getParameter("endTime");
			String description = request.getParameter("description");
			String projectId = request.getHeader("projectId");
			String applyRowGuid = request.getHeader("RowGuid");
			String businessGuid = request.getHeader("synMainId");
			if (!"0".equals(workorderstate)) {
				params.put("workorderstate", workorderstate);
			}
			if (!(startTime == null || "".equals(startTime))) {
				params.put("startTime", startTime);
			}
			if (!(endTime == null || "".equals(endTime))) {
				params.put("endTime", endTime);
			}
			if (!(description == null || "".equals(description))) {
				params.put("description", description);
			}
			// if (!(applyRowGuid==null ||"".equals(applyRowGuid))) {
			// params.put("BusinessGuid", applyRowGuid);
			// }
			if (!(applyRowGuid == null || "".equals(businessGuid))) {
				params.put("BusinessGuid", businessGuid);
			}
			//如果当前用户是租户，那么用他的手机号去查找数据
			if(null!=u && u.getAdmin()==Constant.LESSEE_ROLE) {
				params.put("Phone", u.getAccountNo());
			}
			// 货物放行是2 空调加时是0
			params.put("applyType", "0");
			StringBuffer url = new StringBuffer(Constant.WORK_ORDER_LIST2);
			url.append(projectId);
			// url.append("/200/1");
			url.append("/" + rows + "/" + page);
			String token = TokenUtil.createToken(url.toString(), request, time, params);
			Object[] keys = null;
			if (null != params) {
				keys = params.keySet().toArray();
				Arrays.sort(keys);
				if (null != keys) {
					url.append("?");
					for (Object key : keys) {
						Object value = params.get(key);
						url.append(key);
						url.append("=");
						url.append(String.valueOf(value));
						url.append("&");
					}
				}
				url.append("appkey=").append(Constant.MANAGE_APPKEY).append("&time=").append(time).append("&token=")
						.append(token);
			} else {
				url.append("?appkey=").append(Constant.MANAGE_APPKEY).append("&time=").append(time).append("&token=")
						.append(token);
			}
			System.out.println(url.toString());
			String url1 = Constant.BASE_URL + url.toString();
			String resultStr = HttpUtil.doGet(url1);
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			String errorCode = imisObj.getString("ErrorCode");
			if ("0".equals(errorCode)) {
				JSONObject data = imisObj.getJSONObject("Data");
				JSONArray pageData = data.getJSONArray("pageData");
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
				rm.setData(pageData);
			} else {
				rm.setCodeAndMsg(Integer.parseInt(errorCode), imisObj.getString("ErrorMessage"));
			}
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询空调加时申请列表异常！");
			e.printStackTrace();
		}
		return rm;
	}

	@ApiOperation(value = "获取工单详情", notes = "获取工单详情(货物放行、空调加时）")
	@RequestMapping(value = "/getWorkDetail", method = RequestMethod.GET)
	@ResponseBody
	public ResponseMessage<AirConditioningResult> getWorkDetail(HttpServletRequest request) throws Exception {
		ResponseMessage<AirConditioningResult> rm = new ResponseMessage<AirConditioningResult>();
		long time = System.currentTimeMillis();
		try {
			String workOrdersGuid = request.getParameter("workOrdersGuid");
			// String workOrdersGuid="280dd351-47a6-4b64-bc42-3c13293bbb6c";
			String url = Constant.WORK_DETAIL + workOrdersGuid;
			String token = TokenUtil.createToken(url, request, time, null);
			url = url + "?appkey=" + Constant.MANAGE_APPKEY + "&time=" + time + "&token=" + token;
			String resultStr = HttpUtil.doGet(Constant.BASE_URL + url);
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			String erroeCode = imisObj.getString("ErrorCode");
			if ("0".equals(erroeCode)) {
				JSONObject data = imisObj.getJSONObject("Data");
				JSONObject ifo = data.getJSONObject("WorkOrdersInfo");
				if (null == ifo) {
					rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, "没有数据返回");
					return rm;
				}
				JSONArray timeinfo = ifo.getJSONArray("UseTimeInfo");
				List<UseTime> list = JSON.parseObject(timeinfo.toJSONString(), new TypeReference<List<UseTime>>() {
				});
				Map<String, Object> timeMap = TimeParse.parse(list);
				AirConditioningResult result = new AirConditioningResult();
				result.setDetail(data);
				result.setTimeList(timeMap);
				rm.setData(result);
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			} else {
				rm.setCodeAndMsg(Integer.parseInt(erroeCode), imisObj.getString("ErrorMessage"));
			}
		} catch (Exception e) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("查询空调加时申请详情异常！");
			e.printStackTrace();
		}
		return rm;
	}

	@ApiOperation(value = "空调加时申请", notes = "申请空调加时")
	@RequestMapping(value = "/saveAirConditioning", method = RequestMethod.POST)
	@ResponseBody
	public ResponseMessage<Object> saveAirConditioning(@RequestBody JSONObject jsonParam, HttpServletRequest request) {
		// 调整字段判断和事务的先后顺序 update by eva 209-09-27
		ResponseMessage<Object> rm = new ResponseMessage<>();
		Map<String, Object> params = new HashMap<>();
		String projectId = request.getHeader("projectId");
		String applyRowGuid = request.getHeader("RowGuid");
		if(StringUtils.isEmpty(applyRowGuid)) {
			 applyRowGuid = request.getHeader("synMainId");
		}
 
		AirConditioning airConditioning = JSON.parseObject(jsonParam.toJSONString(),
				new TypeReference<AirConditioning>() {
				});
		if (airConditioning.getUseTimeInfo() == null || airConditioning.getUseTimeInfo().size() < 0) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "申请加时时段不能为空");
			return rm;
		}
		if (StringUtils.isBlank(airConditioning.getApplicant())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "申请人不能为空");
			return rm;
		}
		if (StringUtils.isBlank(airConditioning.getApplicantTel())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "申请人手机不能为空");
			return rm;
		}
		if (StringUtils.isBlank(airConditioning.getRoomInfo())) {
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "申请区域不能为空");
			return rm;
		}
		try {
			boolean flag = airConditioningService.checkExistence(airConditioning.getCompany(),
					airConditioning.getRoomInfo(), airConditioning.getUseTimeInfo(),request);
			if (flag) {
				rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, "该时段已经提交过申请！");
				return rm;
			}
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
//		// 1.获取事务控制管理器
//		DataSourceTransactionManager transactionManager = (DataSourceTransactionManager) SpringContextUtils
//				.getBeanById("transactionManager");
//		// 2.获取事务定义
//		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
//		// 3.设置事务隔离级别，开启新事务
//		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
//		// 4.获得事务状态
//		TransactionStatus status = transactionManager.getTransaction(def);
		int goodCount=0;
		System.out.println("空调加时----jsonParam+++++++++++++-------------------------------" + jsonParam);
		

		long time = System.currentTimeMillis();
		try {
			String url = Constant.WORK_INSERT;
			SimpleDateFormat sdf = DateUtils.sdfDateTime;
			String roomsStr = airConditioning.getRoomInfo();
			List<String> roomList = StringUtils.stringConvertList(roomsStr);
			Room room=null;
			List<Room> roomsList = new ArrayList<Room>();
			for (int i = 0; i < roomList.size(); i++) {
				room = new Room();
				room.setRoomGuid(roomList.get(i));
				roomsList.add(room);
			}
			List<UseTime> useTimeInfoList = airConditioning.getUseTimeInfo();
			params.put("ApplyRowGuid", applyRowGuid);
			params.put("ApplyTime", sdf.format(new Date()).toString());
			params.put("ProjectGuid", projectId);
			params.put("ApplyType", "0");
			params.put("ApplyName", airConditioning.getApplicant());
			params.put("TelPhone", airConditioning.getApplicantTel());
			params.put("Description", airConditioning.getDescription());
			params.put("UseTimeInfo", JSON.toJSONString(useTimeInfoList));
			params.put("RoomInfo", JSON.toJSONString(roomsList));
			Map<String,Object> map=TokenUtil.createToken(url, time, params);
			String token = map.get("token").toString();
			url = url + "?token=" + token;
			params.put("appkey", Constant.MANAGE_APPKEY);
			params.put("time", time);
			params.put("UseTimeInfo", useTimeInfoList);
			params.put("RoomInfo", roomsList);
//			String json = JSON.toJSONString(params);
			String resultStr = HttpUtil.postGeneralUrl(Constant.BASE_URL + url, "application/json,text/json", map.get("parms").toString(),
					"UTF-8");
			//去掉resultStr中的[]
			resultStr = resultStr.replaceAll("\\[", "");
			resultStr = resultStr.replaceAll("\\]", "");
			
			JSONObject imisObj = JSONObject.parseObject(resultStr);
			String errorCode = imisObj.getString("ErrorCode");
			if ("0".equals(errorCode)) {
				JSONObject data = imisObj.getJSONObject("Data");
				AddResult addResult = JSONObject.toJavaObject(data, AddResult.class);
				AirConditionerApply airConditionerApply = new AirConditionerApply();
				airConditionerApply.setApplicant(airConditioning.getApplicant());
				airConditionerApply.setPhone(airConditioning.getApplicantTel());
				airConditionerApply.setApplyArea(roomsStr);
				airConditionerApply.setApplyCompany(airConditioning.getCompany());
				airConditionerApply.setApplyReason(airConditioning.getDescription());
				airConditionerApply.setCreateDate(new Date());
				airConditionerApply.setOperateNo(addResult.getValue());
				goodCount = airConditioningService.save(airConditionerApply);
				for (UseTime useTime : useTimeInfoList) {
					ApplyTime entity = new ApplyTime();
					entity.setStartdate(useTime.getStartDate());
					entity.setEnddate(useTime.getEndDate());
					entity.setStarttime(useTime.getStartTime());
					entity.setEndtime(useTime.getEndTime());
					entity.setOrderid(addResult.getValue());
					airConditioningTimeService.save(entity);
//					System.out.println("测试异常数据"+ 100/0);
				}
				ApplyRecord entity = new ApplyRecord();
				Map<String, Object> userParam = new HashMap<String, Object>();
				userParam.put("openId", request.getHeader("openId"));
				User user = userService.getUserByParams(userParam);
//				userService.getUserByParams(params);
				entity.setUserId(user.getId());
				entity.setTitle("空调加时申请");
				entity.setCreateDate(new Date());
				entity.setOperateNo(addResult.getValue());
				entity.setApplyType("空调加时申请");
				entity.setLocation(airConditioning.getLocation());
				entity.setDescription(airConditioning.getDescription());
				entity.setTypeCode(2);
				entity.setStatus("已提交");
				entity.setPhone(airConditioning.getApplicantTel());
				entity.setProjectId(projectId);
				entity.setSynId(request.getHeader("synId"));
				entity.setSynMainId(request.getHeader("synMainId"));
				applyRecordService.save(entity);
				rm.setCodeAndMsg(ResultCodeEnum.SUCCESS.code, ResultCodeEnum.SUCCESS.msg);
			} else {
				JSONObject data = imisObj.getJSONObject("Data");
				String message = data.getString("FailReason");
				//rm.setCodeAndMsg(Integer.parseInt(errorCode), imisObj.getString("ErrorMessage") + message);
				rm.setCodeAndMsg(Integer.parseInt(errorCode), message);
			}
		} catch (Exception e) {
			goodCount=-1;
			rm.setCodeAndMsg(ResultCodeEnum.ERROR.code, ResultCodeEnum.ERROR.msg);
			log.error("空调加时申请异常！");
			e.printStackTrace();
		}
//		finally {
//			if (goodCount<=0) {
//				//如果获取明细插入失败，那么这条申请也不会成功
//				transactionManager.rollback(status);
//			} else {
//				transactionManager.commit(status);
//			}
//		}
	
		return rm;

	}

}